package com.artlongs.webapp.user.service;

import com.artlongs.base.vo.BizRetCode;
import com.artlongs.base.vo.BizRetVo;
import com.artlongs.common.Enums;
import com.artlongs.webapp.user.dao.AddressDao;
import com.artlongs.webapp.user.dao.UserDao;
import com.artlongs.webapp.user.model.User;
import org.apache.commons.lang.StringUtils;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.Reactor;
import reactor.event.Event;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import static reactor.event.selector.Selectors.$;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    protected UserDao userDao;
    @Resource
    protected GraphDatabaseService graphDb;
    @Resource
    protected Reactor reactor;
    @Resource
    protected AddressDao addressDao;

    public void UserServiceImpl(){


    }

    public User get(Long id) {
        return userDao.findOne(id);
    }

    public Node getNode(Long id) {
        return graphDb.getNodeById(id);
    }


    public BizRetVo del(Long id) {
        BizRetVo bizRetVo = new BizRetVo(BizRetCode.FAIL);
        try {
            userDao.delete(id);
            bizRetVo.setSuccess("删除成功！");
        } catch (Exception e) {
            bizRetVo.setError("删除失败！");
        }

        return bizRetVo;
    }


    /**
     * 更新
     * @param user
     * @return
     */
    public BizRetVo update(User user) {
        BizRetVo bizRetVo = new BizRetVo(BizRetCode.FAIL);
        if(user == null) return bizRetVo;
        try {
            User userDb = get(user.getId());
            if (userDb != null) {
                user.setModifyDate(new Date());
                userDao.save(user.copyTo(user, userDb));
                addressDao.save(user.getAddress());
                bizRetVo.setSuccess("保存成功！");
            }else{
                bizRetVo.setError("用户不存在！");
            }
        } catch (Exception e) {
            bizRetVo.setError("保存失败！");
        }
        return bizRetVo;
    }


	public long countUsers() {
		return userDao.count();
	}
	
	public User createUserByName(String name,String pwd) {
		return userDao.save(new User(name,pwd));
	}
	
	public Iterable<User> getAllUsers() {
		return userDao.findAll();
	}
	
	public User findWorldById(Long id) {
		return userDao.findOne(id);
	}
	
	public User findWorldByName(String name) {
		return userDao.findBySchemaPropertyValue("name", name);
	}
	
	public Iterable<User> findAllByAge(int age) {
		return userDao.findAllBySchemaPropertyValue("age", age);
	}
	
	public Collection<User> makeSomeUsers() {
		Collection<User> users = new ArrayList<User>();

        User leeton = createUserByName("leeton", "123456");
        User neo = createUserByName("neo", "123456");
        User alice = createUserByName("alice", "123456");
        User jocky = createUserByName("jocky", "123456");
        User eya = createUserByName("eya", "123456");


        leeton.addFriend(eya);
        eya.addFriend(jocky);
        jocky.addFriend(eya);

        users.add(leeton);
        users.add(neo);
        users.add(alice);
        users.add(jocky);
        users.add(eya);

        leeton.setFindingType(Enums.Finding.FRIEND);

        // userDao.save(users);
        
        return users;
	}



    public User register(String name, String password) {
        if (name==null || name.isEmpty()) throw new RuntimeException("No name provided.");
        if (password==null || password.isEmpty()) throw new RuntimeException("No password provided.");

        User user=userDao.save(new User(name,password));
        return user;
    }

    public BizRetVo register(User user) {
        BizRetVo bizRetVo = new BizRetVo(BizRetCode.FAIL);
        if (null == user) return bizRetVo;
        String retStr = checkByReg(user);
        if (StringUtils.isNotBlank(retStr)) {
            bizRetVo.setError(retStr);
        }else {
            userDao.save(user);
            bizRetVo.setSuccess("注册成功!");
        }
        return bizRetVo;
    }


    private BizRetVo liseningCreateUser(Event<User> event) {
        BizRetVo bizRetVo = new BizRetVo(BizRetCode.FAIL);
        reactor.on($(UserService.NOTIC_CREATE_USER), (Event<String> ev)->{
            register(event.getData());
            bizRetVo.setSuccess("创建成功");
        }).cancelAfterUse();


        return bizRetVo;

    }



    private String checkByReg(User user) {
        String retStr = "";
        if (StringUtils.isBlank(user.getName())) {
            retStr = "呢称不能为空";
        }else {
            User userDb = userDao.findBySchemaPropertyValue("name", user.getName());
            if (userDb != null) {
                retStr = "呢称已经被注册。";
            }
        }
        if (StringUtils.isBlank(user.getAccount())) {
            retStr = "帐号不能为空";
        }else {
            User userDb = userDao.findBySchemaPropertyValue("account", user.getAccount());
            if (userDb != null) {
                retStr = "帐号已经被注册。";
            }
        }
        if (StringUtils.isBlank(user.getPassword())) {
            retStr = "密码不能为空";
        }

        return retStr;

    }


}
